<?php

namespace app\common\model\xilujob;

use app\common\model\User;
use app\common\library\Auth;
use fast\Random;
use think\Db;
use think\Exception;
use think\Log;
use think\Model;
use traits\model\SoftDelete;
use function fast\array_except;

class XilujobUser extends Model
{

    use SoftDelete;

    // 表名
    protected $name = 'xilujob_user';
    
    // 自动写入时间戳字段
    protected $autoWriteTimestamp = 'int';

    // 定义时间戳字段名
    protected $createTime = 'createtime';
    protected $updateTime = 'updatetime';
    protected $deleteTime = 'deletetime';

    // 追加属性
    protected $append = [
        'actiontime_text',
        'source_text'
    ];

    const GROUP_MEMBER = '1';// 求职用户
    const GROUP_COMPANY = '2';// 企业

    const SOURCE_REGISTER = '0'; //注册
    const SOURCE_BACKEND = '1'; //后台添加
    //const SOURCE_BACKEND_ONLY_RESUME = '2'; //后台添加简历, 用户数据无用
    //const SOURCE_SHARE_LOGIN = '3'; //简历、自助登记用户
    

    
    public function getSourceList()
    {
        return ['0' => __('Source 0'), '1' => __('Source 1')];
    }


    public function getActiontimeTextAttr($value, $data)
    {
        $value = $value ? $value : (isset($data['actiontime']) ? $data['actiontime'] : '');
        return is_numeric($value) ? date("Y-m-d H:i:s", $value) : $value;
    }


    public function getSourceTextAttr($value, $data)
    {
        $value = $value ? $value : (isset($data['source']) ? $data['source'] : '');
        $list = $this->getSourceList();
        return isset($list[$value]) ? $list[$value] : '';
    }

    public function user() {
        return $this->belongsTo(User::class, 'user_id','id',[],'INNER')->setEagerlyType(0);
    }


    /**
     * 切换用户身份
     * @param XilujobUser $xilujobuser
     * @param integer $groupId
     * @return bool
     */
    public static function switchGroup(XilujobUser $xilujobuser, $groupId) {
        if(!in_array($groupId, [1,2])) {
            throw new Exception('invalid arguments');
        }
        if(in_array($groupId, [XilujobUser::GROUP_COMPANY]) && ($xilujobuser->enterprise_group_id && $groupId!=$xilujobuser->enterprise_group_id && $xilujobuser->group_model->audit_status!=0)) {
            throw new Exception('错误的身份切换');
        }
        $data = ['group_id'=>$groupId];
        try {
            Db::startTrans();
            switch ($groupId) {
                case self::GROUP_MEMBER:
                    $member = Member::get(['user_id'=>$xilujobuser->user_id]);
                    if(!$member){
                        Member::create(['user_id'=>$xilujobuser->user_id]);
                    }
                    break;
                case self::GROUP_COMPANY:
                    $company_profile = CompanyProfile::get(['user_id'=>$xilujobuser->user_id]);
                    if(!$company_profile){
                        $company_profile = CompanyProfile::create(['user_id'=>$xilujobuser->user_id]);
                        EnterpriseInfo::create(['company_id'=>$company_profile->id,'user_id' => $xilujobuser->user_id]);
                    }
                    $data['enterprise_group_id'] = $groupId;
                    break;
                default:
                    throw new Exception('never reachable statement');
            }
            $xilujobuser->save($data);
            Db::commit();
            return true;
        }catch (\Exception $e) {
            Log::error($e->getMessage()."\n".$e->getTraceAsString());
            throw $e;
        }
    }


    /**************************************前后台公共******************************************/
    /**
     *新增用户
     * @param string $group , in: ['1','2','3','4']
     * @param $userData
     * @param $enterpriseData
     * @param array $modelData
     * @return string|Model
     * @throws \think\exception\DbException
     */
    public static function add_user($group, $userData, $enterpriseData, $modelData=[],$user_data=[]) {
        $mobile = $userData['mobile'] ?? null;
        $email =  $userData['email'] ?? null;
        if(!$mobile && !$email) {
            throw new Exception('手机号和邮箱，必填一项');
        }
        if(!$user_data){
            $userData['jointime'] = time();
            $user = new User();
            $validator = new \app\admin\validate\User();

            $validator->scene('add', ['username', 'password', 'mobile']);

            if(!$validator->scene('add')->check($userData)) {
                throw new Exception($validator->getError());
            }
            $password = !empty($userData['password'])?$userData['password']: Random::alnum();
            $userData['salt'] = Random::alnum();
            $userData['password'] = (new Auth())->getEncryptPassword($password, $userData['salt']);
            $userData['status'] = 'normal';
            $ret = $user->save($userData);
            if($ret===false) {
                throw new Exception($user->getError());
            }
        }else{
            $password = !empty($userData['password'])?$userData['password']:Random::alnum();
            $userData['salt'] = Random::alnum();
            $userData['password'] = (new Auth())->getEncryptPassword($password, $userData['salt']);
            $userData['status'] = 'normal';
            $ret = $user_data->save($userData);
        }
        switch ($group) {
            case 1:
                $groupModel = new Member();
                break;
            case 2:
                $groupModel = new CompanyProfile();
                break;
//            case 3:
//                $groupModel = new LabourShop();
//                break;
//            case 4:
//                $groupModel = new Trainer();
//                break;
            default:
                throw new Exception('参数错误');
        }
        #对应用户身份表数据
        $xiluuserModel = new XilujobUser();
        $xiluUser = $xiluuserModel->get(['user_id'=>($user_data?$user_data['id']:$user->id)]);
        if(!$user_data || !$xiluUser){
            $xiluuserData['user_id'] = $user_data?$user_data['id']:$user->id;
            $xiluuserData['group_id'] = $group;
            $xiluuserData['source'] = self::SOURCE_REGISTER;
            $ret = $xiluuserModel->save($xiluuserData);
            if($ret===false) {
                throw new Exception($groupModel->getError());
            }
        }
        #对应身份表
        $modelData['user_id'] = $user_data?$user_data['id']:$user->id;
        $ret = $groupModel->save($modelData);
        if($ret===false) {
            throw new Exception($groupModel->getError());
        }

        #企业组数据添加
        if($group != 1) {
            $enterpriseData['user_id'] = $user_data ? $user_data['id'] : $user->id;
            $enterpriseData['company_id'] = $groupModel->id;
//            if($group== self::GROUP_TRAINER) {
//                $xiluuserModel->save(['trainer_group_id'=>$group]);
//            }else {
                if(!$user_data){
                    $xiluuserModel->save(['enterprise_group_id' => $group]);
                }else{
                    $xiluuserModel->where('user_id',$user_data['id'])->update(['enterprise_group_id' => $group]);
                }
//            }
            //默认基础免费数
            $enterpriseData = array_merge([
                'resume_action_num' =>  Config::getdatas('resume_action_num')??0,
                'job_num_limit'     =>  Config::getdatas('job_publish_num')??0,
                'interview_num'     =>  Config::getdatas('interview_num')??0,
                'job_refresh_num'   =>  Config::getdatas('job_refresh_num')??0,
            ],$enterpriseData);
                $enterpriseInfo = EnterpriseInfo::create(array_except($enterpriseData,['benefit_ids']));
                EnterpriseBenefit::save_info($enterpriseInfo,array_intersect_key($enterpriseData, array_flip((array) ['benefit_ids'])));
        }
        return $groupModel;
    }


    public static function edit_user($id, $group, $userData, $enterpriseData, $modelData=[]) {
        $mobile = $userData['mobile'] ?? null;
        $email = $userData['email'] ?? null;
        if(!$mobile && !$email) {
            throw new Exception('手机号和邮箱，必填一项');
        }

        $user = User::get($id);
        $userData =  array_intersect_key($userData, array_flip((array) ['mobile','email','username','password','nickname','avatar','status','salt']));

        $validator = new \app\admin\validate\User([
            'mobile'=>['regex:^1[3456789]\d{9}$','unique:user,mobile,'.$id],
            'email' => ['email','unique:user,email,'.$id],
        ]);

        $validator->scene('edit', ['mobile','email']);

        if(!$validator->scene('edit')->check($userData)) {
            throw new Exception($validator->getError());
        }

        $ret = $user->save($userData);
        //halt($ret);
        if($ret===false) {
            throw new Exception($user->getError());
        }
        if($modelData) {
            switch ($group) {
                case 1:
                    $groupModel = Member::get(['user_id'=>$id]);
                    break;
                case 2:
                    $groupModel = CompanyProfile::get(['user_id'=>$id]);
                    break;
//                case 3:
//                    $groupModel = LabourShop::get($id);
//                    break;
//                case 4:
//                    $groupModel = Trainer::get($id);
//                    break;
                default:
                   throw new Exception('参数错误');
            }
            $xiluuserModel = XilujobUser::get(['user_id'=>$id]);
            #对应用户身份表数据更新
            $xiluuserData['user_id'] = $user->id;
            $xiluuserData['group_id'] = $group;
            $xiluuserData['source'] = XilujobUser::SOURCE_BACKEND;
            $ret = $xiluuserModel->save($xiluuserData);
            if ($ret === false) {
                throw new Exception($xiluuserModel->getError());
            }

            $name = str_replace("\\model\\", "\\validate\\", get_class($groupModel));
            $ret = $groupModel->validate($name . '.edit')->save($modelData);

            if ($ret === false) {
                throw new Exception($groupModel->getError());
            }
        }
        if($group!=1) {
            $enterpriseInfo = EnterpriseInfo::get(['user_id'=>$user->id]);

            $enterpriseInfo->save(array_except($enterpriseData,['benefit_ids']));
            EnterpriseBenefit::save_info($enterpriseInfo, array_intersect_key($enterpriseData, array_flip((array) ['benefit_ids'])));
        }
        return true;
    }


    /*************************************前台需要**********************************************/

    /**
     * 根据当前group_id获取对应的模型， 可能是member 或者其它3个企业身份对应的模型
     * @param $value
     * @param $data
     * @return mixed|null
     */
    public function getGroupModelAttr($value, $data) {
        switch($data['group_id']) {
            case 1:
                return $this->member;
            case 2:
                return $this->company;
            default:
                return null;
        }
    }

    /**
     * 根据enterprise_group_id(企业身份) 获取企业对应的模型
     */
    public function getEnterpriseModelAttr($value, $data) {
        switch($data['enterprise_group_id']) {
            case 2:
                return $this->company;
            case 3:
                return $this->labour;
            case 4:
                return $this->trainer;
            default:
                return null;
        }
    }


    public function member() {
        return $this->belongsTo('Member','user_id','user_id');
    }

    public function company() {
        return $this->belongsTo('CompanyProfile','user_id','user_id');
    }

    public function enterpriseinfo() {
        return $this->belongsTo('EnterpriseInfo','user_id','user_id');
    }



    /**
     * 格式化输入给api接口的返回值, 包含用户账号信息及部分企业账号状态信息
     * @param User $user
     */
    public static function formatApiRet($user) {

        $user->token = (Auth::instance())->getToken();
        $user->visible(['id','group_id','avatar','nickname','token'],true);

        $xiluuserData = self::field('user_id,group_id,enterprise_group_id,source')->where(['user_id'=>$user->id])->find();
        $user->group_id = $xiluuserData['group_id'];
        $user->enterprise_group_id = $xiluuserData['enterprise_group_id'];

        $user->append(['group_model']);
        switch ($xiluuserData->group_id) {
            case self::GROUP_MEMBER:
                $user['group_model'] = $xiluuserData->group_model;
                break;
            case self::GROUP_COMPANY:
                $user['group_model'] = $xiluuserData->group_model->visible(['personal_audit_status','audit_status']);
                break;
        }
        return $user;
    }


}
